package com.fcl.blog.web;

import cn.hutool.core.util.IdUtil;
import com.fcl.blog.comment.Result;
import com.fcl.blog.exception.ServiceException;
import com.fcl.blog.po.Type;
import com.fcl.blog.service.TypeService;
import com.fcl.blog.vo.Page;
import com.fcl.blog.vo.TypeVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 乘凉
 * @Date 2023/10/22 14:45
 * @Version 1.0
 * @description  分类的控制层相关处理
 * @since 1.0
 */
@RestController
@Slf4j
@RequestMapping("/admin")
public class TypeController {
    @Autowired
    private TypeService service;

    @GetMapping("/types")
    public Result getList(){
        PageHelper.startPage(1,7);
        List<Type> listType = service.findListType();
        PageInfo<Type> pageInfo = new PageInfo<>(listType);
        return Result.success(pageInfo);
    }

    @GetMapping("/pageType")
    public Result pageTypes(@RequestParam("pageNum") String page){
        PageHelper.startPage(Integer.parseInt(page),new Page().getPagesize());
        List<Type> listType = service.findListType();
        PageInfo<Type> pageInfo = new PageInfo<>(listType);
        return Result.success(pageInfo);
    }

//    添加分类
    @PostMapping("/addType")
    public Result addType(@RequestBody Type  type) throws ServiceException {
        if (type==null){
            log.error("抱歉，您输入的内容为空");
            return Result.error("抱歉，您输入的内容为空");
        }
        Type one = service.selectByName(type.getName());
        if (one!=null){
            log.error("抱歉，该分类已存在");
            return Result.error("抱歉，该分类已存在");
        }
        type.setId(Long.valueOf(IdUtil.randomUUID().replaceAll("-","").hashCode()));
        service.insertType(type);

        return Result.success("添加成功！");
    }

    @GetMapping("/deType")
    public Result deleteType(@RequestParam("id") String id){
        if (id==null){
           return Result.error("抱歉，该id已经删除或者不存在");
        }
        if (id=="1"){
            return Result.error("抱歉，默认分类不能删除哦");
        }
        int i = service.deleteById(Long.valueOf(id));
        if (i==0){
            return Result.error("删除失败！！");
        }
        return Result.success("修改成功");
    }

//    修改Type
    @PostMapping("/upType")
    public Result updateType(@RequestBody TypeVo typeVo){
        if (typeVo==null){
            return Result.error("抱歉，未获取到数据，或者您输入的内容为空");
        }
        if (typeVo.getId()=="1"){
            return Result.error("抱歉，默认分类不能修改哦");
        }
        int i = service.updateByType(typeVo);
        if (i==0){
            return  Result.error("抱歉，修改失败！！");
        }
        return Result.success("修改成功");
    }
}
